package com.businesscard.system.service.impl;

import com.businesscard.system.entity.UserGroup;
import com.businesscard.system.entity.User;
import com.businesscard.system.mapper.UserGroupMapper;
import com.businesscard.system.service.UserGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 用户组服务实现
 */
@Service
public class UserGroupServiceImpl implements UserGroupService {

    @Autowired
    private UserGroupMapper userGroupMapper;

    @Override
    public boolean createGroup(UserGroup group) {
        return userGroupMapper.insertGroup(group) > 0;
    }

    @Override
    public boolean updateGroup(UserGroup group) {
        return userGroupMapper.updateGroup(group) > 0;
    }

    @Override
    public List<UserGroup> getAllGroups() {
        return userGroupMapper.selectAllGroups();
    }

    @Override
    public UserGroup getGroupById(Integer id) {
        return userGroupMapper.selectGroupById(id);
    }

    @Override
    public UserGroup getGroupByName(String groupName) {
        return userGroupMapper.selectGroupByName(groupName);
    }

    @Override
    @Transactional
    public boolean deleteGroup(Integer id) {
        return userGroupMapper.deleteGroup(id) > 0;
    }

    @Override
    public boolean addUserToGroup(Integer groupId, Integer userId) {
        // 检查用户是否已在用户组中
        if (isUserInGroup(groupId, userId)) {
            return true; // 已在用户组中，视为添加成功
        }
        return userGroupMapper.addUserToGroup(groupId, userId) > 0;
    }

    @Override
    public boolean removeUserFromGroup(Integer groupId, Integer userId) {
        return userGroupMapper.removeUserFromGroup(groupId, userId) > 0;
    }

    @Override
    public List<UserGroup> getGroupsByUserId(Integer userId) {
        return userGroupMapper.selectGroupsByUserId(userId);
    }

    @Override
    public List<User> getUsersByGroupId(Integer groupId) {
        return userGroupMapper.selectUsersByGroupId(groupId);
    }

    @Override
    public boolean isUserInGroup(Integer groupId, Integer userId) {
        Boolean result = userGroupMapper.checkUserInGroup(groupId, userId);
        return result != null && result;
    }
} 